<template>
	<view class="component-page">
		<view class="page-header">
			<view class="back-button" @click="backToHome">
				<text class="back-icon">←</text>
				<text>返回</text>
			</view>
			<text class="page-title">蓝牙连接工具</text>
		</view>
		
		<view class="demo-section">
			<view class="section-title">
				蓝牙设备连接
			</view>
			
			<view class="bluetooth-panel">
				<view class="status-card" :class="[bluetoothStatus]">
					<view class="status-icon">
						<text v-if="bluetoothStatus === 'disconnected'">📵</text>
						<text v-else-if="bluetoothStatus === 'scanning'">🔄</text>
						<text v-else-if="bluetoothStatus === 'connected'">✅</text>
						<text v-else>⚠️</text>
					</view>
					<view class="status-info">
						<text class="status-title">{{ getStatusTitle() }}</text>
						<text class="status-desc">{{ connectedDevice ? `已连接: ${connectedDevice.name || connectedDevice.deviceId}` : getStatusDesc() }}</text>
					</view>
				</view>
				
				<view class="action-buttons">
					<button 
						class="action-button scan-btn" 
						:disabled="bluetoothStatus === 'scanning'" 
						@click="startScan"
					>
						{{ bluetoothStatus === 'scanning' ? '扫描中...' : '扫描设备' }}
					</button>
					
					<button 
						class="action-button stop-btn" 
						:disabled="bluetoothStatus !== 'scanning'" 
						@click="stopScan"
					>
						停止扫描
					</button>
				</view>
				
				<view class="device-list" v-if="deviceList.length > 0">
					<view class="list-header">
						<text class="header-title">发现的设备</text>
						<text class="header-count">{{ deviceList.length }}个</text>
					</view>
					
					<view 
						class="device-item" 
						v-for="(device, index) in deviceList" 
						:key="index"
						:class="{ 'connected': connectedDevice && connectedDevice.deviceId === device.deviceId }"
						@click="connectDevice(device)"
					>
						<view class="device-icon">
							<text v-if="device.deviceType === 'classic'">🎧</text>
							<text v-else-if="device.deviceType === 'ble'">📱</text>
							<text v-else-if="device.deviceType === 'dual'">🖨️</text>
							<text v-else>📟</text>
						</view>
						<view class="device-info">
							<text class="device-name">{{ device.name || '未知设备' }}</text>
							<text class="device-id">{{ device.deviceId }}</text>
							<text class="device-rssi">信号强度: {{ device.RSSI || 'N/A' }}</text>
						</view>
						<text class="device-action" v-if="connectedDevice && connectedDevice.deviceId === device.deviceId">
							已连接
						</text>
						<text class="device-action" v-else>
							连接
						</text>
					</view>
				</view>
				
				<view class="empty-list" v-else-if="bluetoothStatus === 'scanning'">
					<text class="empty-icon">🔍</text>
					<text class="empty-text">正在搜索附近的蓝牙设备...</text>
				</view>
				
				<view class="empty-list" v-else>
					<text class="empty-icon">📵</text>
					<text class="empty-text">未发现蓝牙设备，请点击扫描按钮</text>
				</view>
			</view>
		</view>
		
		<view class="demo-section" v-if="connectedDevice">
			<view class="section-title">
				设备控制
			</view>
			
			<view class="control-panel">
				<view class="control-card">
					<view class="card-header">
						<text class="card-title">设备信息</text>
					</view>
					<view class="card-content">
						<view class="info-row">
							<text class="info-label">设备名称</text>
							<text class="info-value">{{ connectedDevice.name || '未知设备' }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">设备ID</text>
							<text class="info-value">{{ connectedDevice.deviceId }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">连接时间</text>
							<text class="info-value">{{ formatConnectTime() }}</text>
						</view>
					</view>
				</view>
				
				<view class="control-actions">
					<button class="control-button send-btn" @click="sendTestData">发送测试数据</button>
					<button class="control-button disconnect-btn" @click="disconnectDevice">断开连接</button>
				</view>
				
				<view class="log-panel">
					<view class="log-header">
						<text class="log-title">通信日志</text>
						<text class="log-clear" @click="clearLogs">清除</text>
					</view>
					<scroll-view class="log-content" scroll-y>
						<view 
							class="log-item" 
							v-for="(log, index) in logList" 
							:key="index"
							:class="[log.type]"
						>
							<text class="log-time">{{ log.time }}</text>
							<text class="log-message">{{ log.message }}</text>
						</view>
						<view class="log-empty" v-if="logList.length === 0">
							<text>暂无日志记录</text>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		
		<view class="demo-section">
			<view class="section-title">功能特性</view>
			<view class="feature-list">
				<view class="feature-item">
					<view class="feature-icon">🔍</view>
					<view class="feature-info">
						<text class="feature-title">自动设备发现</text>
						<text class="feature-desc">快速扫描并显示周边蓝牙设备</text>
					</view>
				</view>
				<view class="feature-item">
					<view class="feature-icon">🔗</view>
					<view class="feature-info">
						<text class="feature-title">多种协议支持</text>
						<text class="feature-desc">支持BLE和经典蓝牙连接</text>
					</view>
				</view>
				<view class="feature-item">
					<view class="feature-icon">📶</view>
					<view class="feature-info">
						<text class="feature-title">自动重连机制</text>
						<text class="feature-desc">断开连接后智能尝试重新连接</text>
					</view>
				</view>
				<view class="feature-item">
					<view class="feature-icon">🔌</view>
					<view class="feature-info">
						<text class="feature-title">跨平台适配</text>
						<text class="feature-desc">适配iOS、Android和各类小程序</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { create } from '@/components/xl-bluetooth';

// 蓝牙状态，可能的值: disconnected, scanning, connecting, connected, error
const bluetoothStatus = ref('disconnected');
// 设备列表
const deviceList = ref([]);
// 已连接的设备
const connectedDevice = ref(null);
// 日志列表
const logList = ref([]);
// 连接时间
const connectTime = ref(null);
// 蓝牙实例
const bluetooth = ref(null);

// 初始化蓝牙
const initBluetooth = async () => {
	try {
		bluetooth.value = create();
		await bluetooth.value.initialize();
		addLog('info', '蓝牙初始化成功');
		bluetoothStatus.value = 'disconnected';
	} catch (error) {
		addLog('error', '蓝牙初始化失败: ' + error.message);
		bluetoothStatus.value = 'error';
	}
};

// 开始扫描
const startScan = async () => {
	if (!bluetooth.value) {
		await initBluetooth();
	}
	
	try {
		bluetoothStatus.value = 'scanning';
		addLog('info', '开始扫描设备...');
		await bluetooth.value.startScan({
			success: () => {
				// 监听设备状态变化
				const status = bluetooth.value.getStatus();
				deviceList.value = status.devices || [];
			},
			fail: (error) => {
				addLog('error', '扫描失败: ' + error.message);
				bluetoothStatus.value = 'error';
			}
		});
	} catch (error) {
		addLog('error', '扫描失败: ' + error.message);
		bluetoothStatus.value = 'error';
	}
};

// 停止扫描
const stopScan = async () => {
	if (!bluetooth.value) return;
	
	try {
		await bluetooth.value.stopScan();
		bluetoothStatus.value = 'disconnected';
		addLog('info', '停止扫描');
	} catch (error) {
		addLog('error', '停止扫描失败: ' + error.message);
	}
};

// 连接设备
const connectDevice = async (device) => {
	if (!bluetooth.value) return;
	
	try {
		bluetoothStatus.value = 'connecting';
		addLog('info', `正在连接设备: ${device.name || device.deviceId}`);
		
		await bluetooth.value.connect(device.deviceId, {
			success: () => {
				bluetoothStatus.value = 'connected';
				connectedDevice.value = device;
				connectTime.value = Date.now();
				addLog('success', '设备连接成功');
			},
			fail: (error) => {
				bluetoothStatus.value = 'error';
				addLog('error', '连接失败: ' + error.message);
			}
		});
	} catch (error) {
		bluetoothStatus.value = 'error';
		addLog('error', '连接失败: ' + error.message);
	}
};

// 断开连接
const disconnectDevice = async () => {
	if (!bluetooth.value || !connectedDevice.value) return;
	
	try {
		await bluetooth.value.disconnect();
		bluetoothStatus.value = 'disconnected';
		connectedDevice.value = null;
		connectTime.value = null;
		addLog('info', '设备已断开连接');
	} catch (error) {
		addLog('error', '断开连接失败: ' + error.message);
	}
};

// 发送测试数据
const sendTestData = async () => {
	if (!bluetooth.value || !connectedDevice.value) return;
	
	try {
		await bluetooth.value.sendData('test data', {
			success: () => {
				addLog('success', '测试数据发送成功');
			},
			fail: (error) => {
				addLog('error', '发送数据失败: ' + error.message);
			}
		});
	} catch (error) {
		addLog('error', '发送数据失败: ' + error.message);
	}
};

// 添加日志
const addLog = (type, message) => {
	logList.value.unshift({
		type,
		message,
		time: new Date().toLocaleTimeString()
	});
	
	// 最多保留100条日志
	if (logList.value.length > 100) {
		logList.value = logList.value.slice(0, 100);
	}
};

// 清除日志
const clearLogs = () => {
	logList.value = [];
};

// 格式化连接时间
const formatConnectTime = () => {
	if (!connectTime.value) return '未连接';
	const diff = Date.now() - connectTime.value;
	const minutes = Math.floor(diff / 60000);
	const seconds = Math.floor((diff % 60000) / 1000);
	return `${minutes}分${seconds}秒`;
};

// 获取状态标题
const getStatusTitle = () => {
	switch (bluetoothStatus.value) {
		case 'disconnected':
			return '未连接设备';
		case 'scanning':
			return '正在扫描';
		case 'connecting':
			return '正在连接';
		case 'connected':
			return '已连接';
		case 'error':
			return '连接异常';
		default:
			return '未知状态';
	}
};

// 获取状态描述
const getStatusDesc = () => {
	switch (bluetoothStatus.value) {
		case 'disconnected':
			return '点击扫描按钮开始搜索设备';
		case 'scanning':
			return '正在搜索附近的蓝牙设备...';
		case 'connecting':
			return '正在尝试连接设备...';
		case 'error':
			return '蓝牙连接出现问题，请重试';
		default:
			return '';
	}
};

// 返回首页
const backToHome = () => {
	uni.navigateBack();
};

// 生命周期钩子
onMounted(() => {
	initBluetooth();
});

onUnmounted(() => {
	if (bluetooth.value) {
		stopScan();
		if (connectedDevice.value) {
			disconnectDevice();
		}
	}
});
</script>

<style lang="scss">
.component-page {
	padding: 30rpx;
	background-color: #f7f7f7;
	min-height: 100vh;
	box-sizing: border-box;
}

.page-header {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
	
	.back-button {
		display: flex;
		align-items: center;
		padding: 10rpx 0;
		margin-right: 20rpx;
		
		.back-icon {
			font-size: 36rpx;
			margin-right: 6rpx;
		}
	}
	
	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
}

.demo-section {
	margin-bottom: 30rpx;
	
	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
}

.bluetooth-panel {
	background-color: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;
	
	.status-card {
		display: flex;
		align-items: center;
		padding: 30rpx;
		
		&.disconnected {
			background-color: #f9f9f9;
		}
		
		&.scanning {
			background-color: #e5f7ff;
		}
		
		&.connecting {
			background-color: #fff5e5;
		}
		
		&.connected {
			background-color: #e5ffe5;
		}
		
		&.error {
			background-color: #ffe5e5;
		}
		
		.status-icon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
			margin-right: 20rpx;
		}
		
		.status-info {
			flex: 1;
			
			.status-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 6rpx;
			}
			
			.status-desc {
				font-size: 26rpx;
				color: #666;
			}
		}
	}
	
	.action-buttons {
		display: flex;
		padding: 20rpx 30rpx;
		border-bottom: 1px solid #f5f5f5;
		
		.action-button {
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 28rpx;
			border-radius: 40rpx;
			
			&.scan-btn {
				background-color: #007aff;
				color: #fff;
				margin-right: 20rpx;
				
				&:disabled {
					opacity: 0.6;
				}
			}
			
			&.stop-btn {
				background-color: #f5f5f5;
				color: #666;
				
				&:disabled {
					opacity: 0.6;
					color: #999;
				}
			}
		}
	}
	
	.list-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		
		.header-title {
			font-size: 28rpx;
			font-weight: bold;
			color: #333;
		}
		
		.header-count {
			font-size: 24rpx;
			color: #666;
			background-color: #f5f5f5;
			padding: 6rpx 16rpx;
			border-radius: 30rpx;
		}
	}
	
	.device-list {
		max-height: 600rpx;
		overflow-y: auto;
		
		.device-item {
			display: flex;
			align-items: center;
			padding: 24rpx 30rpx;
			border-bottom: 1px solid #f5f5f5;
			
			&:last-child {
				border-bottom: none;
			}
			
			&.connected {
				background-color: rgba(0, 122, 255, 0.05);
			}
			
			.device-icon {
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				background-color: #f5f5f5;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 30rpx;
				margin-right: 20rpx;
			}
			
			.device-info {
				flex: 1;
				
				.device-name {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 4rpx;
				}
				
				.device-id {
					font-size: 22rpx;
					color: #999;
					margin-bottom: 4rpx;
				}
				
				.device-rssi {
					font-size: 22rpx;
					color: #666;
				}
			}
			
			.device-action {
				font-size: 24rpx;
				padding: 8rpx 20rpx;
				border-radius: 30rpx;
				background-color: #f5f5f5;
				color: #333;
			}
			
			&.connected .device-action {
				background-color: #007aff;
				color: #fff;
			}
		}
	}
	
	.empty-list {
		padding: 60rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.empty-icon {
			font-size: 80rpx;
			margin-bottom: 20rpx;
		}
		
		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}
}

.control-panel {
	background-color: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;
	
	.control-card {
		padding: 20rpx 30rpx;
		border-bottom: 1px solid #f5f5f5;
		
		.card-header {
			margin-bottom: 20rpx;
			
			.card-title {
				font-size: 28rpx;
				font-weight: bold;
				color: #333;
			}
		}
		
		.card-content {
			.info-row {
				display: flex;
				margin-bottom: 16rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.info-label {
					width: 150rpx;
					font-size: 26rpx;
					color: #999;
				}
				
				.info-value {
					flex: 1;
					font-size: 26rpx;
					color: #333;
				}
			}
		}
	}
	
	.control-actions {
		display: flex;
		padding: 20rpx 30rpx;
		border-bottom: 1px solid #f5f5f5;
		
		.control-button {
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 28rpx;
			border-radius: 40rpx;
			
			&.send-btn {
				background-color: #4cd964;
				color: #fff;
				margin-right: 20rpx;
			}
			
			&.disconnect-btn {
				background-color: #ff3b30;
				color: #fff;
			}
		}
	}
	
	.log-panel {
		padding: 20rpx 30rpx;
		
		.log-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			
			.log-title {
				font-size: 28rpx;
				font-weight: bold;
				color: #333;
			}
			
			.log-clear {
				font-size: 24rpx;
				color: #007aff;
			}
		}
		
		.log-content {
			height: 300rpx;
			background-color: #f9f9f9;
			border-radius: 8rpx;
			padding: 16rpx;
			
			.log-item {
				margin-bottom: 12rpx;
				font-size: 24rpx;
				
				.log-time {
					color: #999;
					margin-right: 10rpx;
				}
				
				.log-message {
					color: #333;
					word-break: break-all;
				}
				
				&.info .log-message {
					color: #666;
				}
				
				&.success .log-message {
					color: #4cd964;
				}
				
				&.error .log-message {
					color: #ff3b30;
				}
				
				&.send .log-message {
					color: #5856d6;
				}
				
				&.receive .log-message {
					color: #ff9500;
				}
			}
			
			.log-empty {
				display: flex;
				justify-content: center;
				align-items: center;
				height: 100%;
				color: #999;
				font-size: 26rpx;
			}
		}
	}
}

.feature-list {
	background-color: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;
	padding: 10rpx 0;
	
	.feature-item {
		display: flex;
		align-items: center;
		padding: 24rpx 30rpx;
		border-bottom: 1px solid #f5f5f5;
		
		&:last-child {
			border-bottom: none;
		}
		
		.feature-icon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 16rpx;
			background: linear-gradient(45deg, #0396FF, #ABDCFF);
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
			margin-right: 24rpx;
		}
		
		.feature-info {
			flex: 1;
			
			.feature-title {
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 6rpx;
				display: block;
			}
			
			.feature-desc {
				font-size: 26rpx;
				color: #666;
				display: block;
			}
		}
	}
}
</style> 